package com.smartfast4j.springboot.mybatis.demo.controller;

import com.smartfast4j.springboot.mybatis.demo.pojo.LearnResource;
import com.smartfast4j.springboot.mybatis.demo.service.LearnResourceService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * restful api来展示
 * Created by gacl on 2017/11/17.
 */
@RestController
@RequestMapping("/learnResource")
public class LearnResourceController {

    @Autowired
    private LearnResourceService learnResourceService;

   @GetMapping("/list")//@GetMapping("/list")等价于@RequestMapping(value = "/list",method = RequestMethod.GET)
    public List<LearnResource> getLearnResouceList(){
        return learnResourceService.selectByExample(null);
    }

    @GetMapping("/{id}")
    public  LearnResource getLearnResouceById(@PathVariable("id") Long id){
        return learnResourceService.queryLearnResourceById(id);
    }

    @RequestMapping("/add")
    public Map<String,Object> add(LearnResource learnResouce){
        Map<String,Object> dataMap = new HashMap<>();
        if(StringUtils.isBlank(learnResouce.getAuthor())){
            dataMap.put("msg","作者不能为空!");
            dataMap.put("code",-1);
            return dataMap;
        }
        if(StringUtils.isBlank(learnResouce.getTitle())){
            dataMap.put("msg","教程名称不能为空!");
            dataMap.put("code",-1);
            return dataMap;
        }
        if(StringUtils.isBlank(learnResouce.getUrl())){
            dataMap.put("msg","教程链接地址不能为空!");
            dataMap.put("code",-1);
            return dataMap;
        }
        int result = learnResourceService.add(learnResouce);
        if(result>0){
            dataMap.put("msg","教程添加成功!");
            dataMap.put("code",0);
            return dataMap;
        }else{
            dataMap.put("msg","教程添加失败!");
            dataMap.put("code",-1);
            return dataMap;
        }
    }
}
